/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.core.convert.Convert;
import me.zhengjie.modules.biz.domain.PrinterTask;
import me.zhengjie.modules.biz.domain.Settings;
import me.zhengjie.modules.biz.repository.SettingsRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.PrinterTaskRepository;
import me.zhengjie.modules.biz.service.PrinterTaskService;
import me.zhengjie.modules.biz.service.dto.PrinterTaskDto;
import me.zhengjie.modules.biz.service.dto.PrinterTaskQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.PrinterTaskMapper;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author wanghaonan
* @date 2023-03-27
**/
@Service
@RequiredArgsConstructor
public class PrinterTaskServiceImpl implements PrinterTaskService {

    private final PrinterTaskRepository printerTaskRepository;
    private final PrinterTaskMapper printerTaskMapper;
    private final SettingsRepository settingsRepository;

    @Override
    public Map<String,Object> queryAll(PrinterTaskQueryCriteria criteria, Pageable pageable){
        Specification<PrinterTask> specification =  (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(criteriaBuilder.equal(root.get("status"), 0));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<PrinterTask> page = printerTaskRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(printerTaskMapper::toDto));
    }

    @Override
    public List<PrinterTaskDto> queryAll(PrinterTaskQueryCriteria criteria){
        return printerTaskMapper.toDto(printerTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PrinterTaskDto findById(Integer id) {
        PrinterTask printerTask = printerTaskRepository.findById(id).orElseGet(PrinterTask::new);
        ValidationUtil.isNull(printerTask.getId(),"PrinterTask","id",id);
        return printerTaskMapper.toDto(printerTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Integer itemType, Integer itemId, Integer codeType ,HttpServletRequest request) {
        PrinterTask printerTask = new PrinterTask();
        printerTask.setStatus(0);
        printerTask.setIp(StringUtils.getIpAddr(request));
        printerTask.setCodeType(codeType);
        printerTask.setItemId(itemId);
        printerTask.setItemType(itemType);
        List<Settings> settingsList = settingsRepository.findSizeByKey();
        HashMap<String,Integer> config = new HashMap<>();

        for (Settings settings : settingsList) {
            config.put(settings.getKey(), Convert.toInt(settings.getValue()));
        }
        if(itemType == 1){
            printerTask.setSize(config.get("equipment_qrcode_size"));
        } else if (itemType == 2) {
            printerTask.setSize(config.get("substance_qrcode_size"));
        }else {
            printerTask.setSize(config.get("reagent_qrcode_size"));
        }

        printerTaskRepository.save(printerTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PrinterTask resources) {
        PrinterTask printerTask = printerTaskRepository.findById(resources.getId()).orElseGet(PrinterTask::new);
        ValidationUtil.isNull( printerTask.getId(),"PrinterTask","id",resources.getId());
        printerTask.copy(resources);
        printerTaskRepository.save(printerTask);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            printerTaskRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PrinterTaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PrinterTaskDto printerTask : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("IP地址", printerTask.getIp());
            map.put("类型杂物:1，危化品:2", printerTask.getItemType());
            map.put("对应物品的ID", printerTask.getItemId());
            map.put("码类型, 条码:1，二维码:2", printerTask.getCodeType());
            map.put("创建人", printerTask.getCreatorId());
            map.put("状态 0未打印，1已打印", printerTask.getStatus());
            map.put("创建时间", printerTask.getCreatedAt());
            map.put("修改时间", printerTask.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean createTasks(Integer itemType, int[] itemIds, Integer codeType, HttpServletRequest request) {
        if (itemIds.length < 1) {
            return false;
        } else {
            for (Integer itemId : itemIds) {
                PrinterTask printerTask = new PrinterTask();
                printerTask.setStatus(0);
                printerTask.setIp(StringUtils.getIpAddr(request));
                printerTask.setCodeType(codeType);
                printerTask.setItemId(itemId);
                printerTask.setItemType(itemType);
                printerTaskRepository.save(printerTask);
            }
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void complete(Integer id) {
        PrinterTask printerTask = printerTaskRepository.findById(id).orElseGet(PrinterTask::new);
        ValidationUtil.isNull( printerTask.getId(),"PrinterTask","id",id);
        printerTask.setStatus(1);
        printerTaskRepository.save(printerTask);
    }

    @Override
    public List<PrinterTask> queryAllList(HttpServletRequest request) {
        String ip = StringUtils.getIpAddr(request);
        return printerTaskRepository.findAllPrint(ip);
    }
}
